package com.agu.mgt.fms.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.agu.common.annotation.SysLog;
import com.agu.common.excel.Column;
import com.agu.common.excel.ExcelExport;
import com.agu.entity.address.EntAddressEntity;
import com.agu.entity.common.CmmUploadFilesEntity;
import com.agu.entity.fms.FsmsSendEntity;
import com.agu.entity.fsmsmgt.FsmsTemplateEntity;
import com.agu.mgt.address.service.EntAddressService;
import com.agu.mgt.common.service.CmmUploadFilesService;
import com.agu.mgt.fms.service.FsmsSendService;
import com.agu.mgt.sys.controller.AbstractController;
import com.agu.result.Result;
import com.agu.result.ResultGenerator;
import com.agu.utils.CompareUtils;
import com.agu.utils.JsonUtils;
import com.agu.utils.Query;
import com.agu.utils.xss.XssHttpServletRequestWrapper;
import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JavaType;
import com.github.pagehelper.Page;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 发送表
 * 
 * @author 
 * @email 
 * @date 2019-01-22 09:41:04
 */
 @SuppressWarnings("rawtypes")
@RestController
@Api("发送表")
@RequestMapping("fsmssend")
public class FsmsSendController extends AbstractController{
	@Autowired
	private FsmsSendService fsmsSendService;
	
	@Autowired
	private EntAddressService entAddressService;
	
	@Autowired
	private CmmUploadFilesService cmmUploadFilesService;
	
	/**
	 * 列表
	 */
	@RequestMapping("/list")
	@ApiOperation(value = "列表", notes = "说明")
	@RequiresPermissions("fsmssend:list")
	public Result list(@RequestBody Map params){

		// 查询列表数据
		Query query = new Query(params);
		Page<FsmsSendEntity> page = fsmsSendService.queryPageList(query);
		return ResultGenerator.successPage(page);
	}
	
	@RequestMapping("/templist")
	@ApiOperation(value = "模板列表", notes = "说明")
	@RequiresPermissions("fsmssend:list")
	public Result templist(){

		
		Map map = new HashMap();
		
		map.put("spId", this.getSpId());
		
		// 查询列表数据
		@SuppressWarnings("unchecked")
		List<FsmsSendEntity> list = fsmsSendService.queryTemplateList(map);
		
		
		return ResultGenerator.successData(list);
	}
	
	@RequestMapping("/addresslist")
	@ApiOperation(value = "通讯录列表", notes = "说明")
	@RequiresPermissions("fsmssend:list")
	public Result addresslist(){

		
		Map map = new HashMap();
		
		map.put("spId", this.getSpId());
		
		// 查询列表数据
		@SuppressWarnings("unchecked")
		List<EntAddressEntity> list = fsmsSendService.queryAddressList(map);
		
		
		return ResultGenerator.successData(list);
	}
	
	
	@GetMapping("/templateinfo/{id}")
	@ApiOperation(value = "信息", notes = "说明")
	@RequiresPermissions("fsmssend:info")
	public Result queryTemplateInfo(@PathVariable("id") Integer id){
		
		FsmsTemplateEntity fsmsSendCanvas = fsmsSendService.queryTemplateInfo(id);
		
		return ResultGenerator.successData(fsmsSendCanvas);
	}
	
	
	/**
	 * 信息
	 */
	@GetMapping("/info/{sendId}")
	@ApiOperation(value = "信息", notes = "说明")
	@RequiresPermissions("fsmssend:info")
	public Result info(@PathVariable("sendId") String sendId){
		FsmsSendEntity fsmsSend = fsmsSendService.queryObject(sendId);
		
		return ResultGenerator.successData(fsmsSend);
	}
	
	/**
	 * 保存
	 */
	@SysLog("新增发送表")
	@PostMapping("/save")
	@ApiOperation(value = "保存", notes = "说明")
	@RequiresPermissions("fsmssend:save")
	public Result save(@RequestBody FsmsSendEntity fsmsSend){
		
		fsmsSend.setCreateTime(new Date());
		fsmsSend.setCreateUserId(this.getUserId());
		fsmsSend.setSpId(this.getSpId());
		
		if(this.getSpId() == 0)
		{
			return ResultGenerator.fail("非法操作");
		}
		
		//输入手机号码
		if(fsmsSend.getAddressFlag() == 1)
		{
			String mobilesTxt = fsmsSend.getAddressMobile();
			Set mobilesSet = new HashSet();

			String reg = "^[1][0-9]{10}$";
			Pattern p = Pattern.compile(reg);

			if (StringUtils.isNotBlank(mobilesTxt)) {
				String[] strs = mobilesTxt.split(";");
				for (String str : strs) {
					if (str != null) {
						if (Pattern.matches(reg, str.trim())) {
							mobilesSet.add(str.trim());
						}
					}
				}
				fsmsSend.setMobileNum(mobilesSet.size());
				fsmsSend.setAddressMobile(JsonUtils.toJson(mobilesSet));
			} else {
				fsmsSend.setMobileNum(0);
				return ResultGenerator.fail("请检查输入的手机号码是否正确");
			}
		}
		
		//通讯录
		if(fsmsSend.getAddressFlag() == 2)
		{
			Map<String, Object> map = new HashMap();
			map.put("spId", this.getSpId());
			map.put("addressIds", fsmsSend.getAddressIdList());
			
			List<EntAddressEntity> list = entAddressService.querySelectList(map);
			Set mobilesSet = new HashSet();
			JavaType javaType = JsonUtils.getCollectionType(ArrayList.class, String.class);
			
			for(EntAddressEntity item:list)
			{
				String  json  = item.getMobiles();
				
				try {
					List<String> mobileList = JsonUtils.deserialize(json, javaType);
					
					mobilesSet.addAll(mobileList);
					
				} catch (JsonParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			
			fsmsSend.setMobileNum(mobilesSet.size());
			fsmsSend.setAddressMobile(JsonUtils.toJson(mobilesSet));
			
			if(mobilesSet.size() == 0)
			{
				fsmsSend.setMobileNum(0);
				return ResultGenerator.fail("请检查选择的通讯录中是否有正确的手机号码");
			}
		}
		
		//上传号码
		if(fsmsSend.getAddressFlag() == 3)
		{
			CmmUploadFilesEntity file =	cmmUploadFilesService.queryObject(fsmsSend.getFileId());
			Set mobilesSet = new HashSet();
			JavaType javaType = JsonUtils.getCollectionType(ArrayList.class, String.class);
			
			String json = file.getMobileList();
			try {
				List<String> mobileList = JsonUtils.deserialize(json, javaType);
				
				mobilesSet.addAll(mobileList);
				
			} catch (JsonParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			fsmsSend.setMobileNum(mobilesSet.size());
			fsmsSend.setAddressMobile(JsonUtils.toJson(mobilesSet));
			
			if(mobilesSet.size() == 0)
			{
				fsmsSend.setMobileNum(0);
				return ResultGenerator.fail("请检查上传的文件是否有正确的手机号码");
			}
			
		}
		
	
		fsmsSendService.save(fsmsSend);
		
		//处理日志
		Map<String,String> cmap = new HashMap<String,String>();
		     cmap.put("sendId","发送ID");
		     cmap.put("remark","备注");
		     cmap.put("templateId","模板ID");
		     cmap.put("sourceNum","源号码扩展号");
		     cmap.put("sendFlag","发送标识");
		     cmap.put("planSendTime","计划发送时间");
		     cmap.put("addressMobile","发送电话本");
		     cmap.put("mobileNum","电话号码数");
		     cmap.put("spId","spId");
		     cmap.put("spName","sp名称");
		     cmap.put("sendTime","发送时间");
		     cmap.put("endTime","结束时间");
		     cmap.put("checkTime","审批时间");
		     cmap.put("checkState","审批状态");
		     cmap.put("checkMsg","审批意见");
		     cmap.put("checkUser","审批人ID");
		     cmap.put("sendState","发送状态");
		     cmap.put("createUserId","创建用户");
		     cmap.put("createTime","创建时间");
		String remark = CompareUtils.getObjectRemark(fsmsSend, cmap);
		return ResultGenerator.success("保存成功").setRemark(remark);
	}
	
	/**
	 * 修改
	 */
	@SysLog("修改发送表")
	@PostMapping("/update")
	@ApiOperation(value = "修改", notes = "说明")
	@RequiresPermissions("fsmssend:update")
	public Result update(@RequestBody FsmsSendEntity fsmsSend){
	
		FsmsSendEntity fsmsSend1 = fsmsSendService.queryObject(fsmsSend.getSendId());
	
		fsmsSendService.update(fsmsSend);
		
		//处理日志
		Map<String,String> cmap = new HashMap<String,String>();
		
		     cmap.put("sendId","发送ID");
		     cmap.put("remark","备注");
		     cmap.put("templateId","模板ID");
		     cmap.put("sourceNum","源号码扩展号");
		     cmap.put("sendFlag","发送标识");
		     cmap.put("planSendTime","计划发送时间");
		     cmap.put("addressMobile","发送电话本");
		     cmap.put("mobileNum","电话号码数");
		     cmap.put("spId","spId");
		     cmap.put("spName","sp名称");
		     cmap.put("sendTime","发送时间");
		     cmap.put("endTime","结束时间");
		     cmap.put("checkTime","审批时间");
		     cmap.put("checkState","审批状态");
		     cmap.put("checkMsg","审批意见");
		     cmap.put("checkUser","审批人ID");
		     cmap.put("sendState","发送状态");
		     cmap.put("createUserId","创建用户");
		     cmap.put("createTime","创建时间");
	
		String remark = CompareUtils.getTwoObjectRemark(fsmsSend1, fsmsSend, cmap);
	
		return ResultGenerator.success("修改成功").setRemark(remark);
	}
	
	/**
	 * 删除
	 */
	@SysLog("删除发送表")
	@GetMapping("/delete/{sendId}")
	@ApiOperation(value = "删除", notes = "说明")
	@RequiresPermissions("fsmssend:delete")
	public Result delete(@PathVariable("sendId") String sendId){
	
	    	if (sendId == null) {
			return ResultGenerator.fail("缺少参数");
		}
	
		FsmsSendEntity fsmsSend = fsmsSendService.queryObject(sendId);
	
		fsmsSendService.delete(sendId);
		
		//处理日志
		Map<String,String> cmap = new HashMap<String,String>();
		     cmap.put("sendId","发送ID");
		     cmap.put("remark","备注");
		     cmap.put("templateId","模板ID");
		     cmap.put("sourceNum","源号码扩展号");
		     cmap.put("sendFlag","发送标识");
		     cmap.put("planSendTime","计划发送时间");
		     cmap.put("addressMobile","发送电话本");
		     cmap.put("mobileNum","电话号码数");
		     cmap.put("spId","spId");
		     cmap.put("spName","sp名称");
		     cmap.put("sendTime","发送时间");
		     cmap.put("endTime","结束时间");
		     cmap.put("checkTime","审批时间");
		     cmap.put("checkState","审批状态");
		     cmap.put("checkMsg","审批意见");
		     cmap.put("checkUser","审批人ID");
		     cmap.put("sendState","发送状态");
		     cmap.put("createUserId","创建用户");
		     cmap.put("createTime","创建时间");
		String remark = CompareUtils.getObjectRemark(fsmsSend, cmap);
		return ResultGenerator.success("删除成功").setRemark(remark);
	}
	
	/**
	 * 批量删除
	 */
	@SysLog("批量删除发送表")
	@PostMapping("/deletes")
	@ApiOperation(value = "删除", notes = "说明")
	@RequiresPermissions("fsmssend:delete")
	public Result deletes(@RequestBody String[] sendIds){
	
		fsmsSendService.deleteBatch(sendIds);
		
		return ResultGenerator.success("删除成功");
	}
	
	@RequestMapping("/download")
	@ApiOperation(value = "下载", notes = "说明")
	@RequiresPermissions("fsmssend:list")
	public void download(HttpServletRequest request, HttpServletResponse response) {

		HttpServletRequest orgRequest = XssHttpServletRequestWrapper.getOrgRequest(request);
		
		String query = orgRequest.getParameter("query");

		HashMap querymap = JSON.parseObject(query, HashMap.class);

		List<FsmsSendEntity> list = fsmsSendService.queryList(querymap);

		if (list != null && list.size() > 0) {
			Map map = new HashMap();

               Map<Integer, String> sendFlagMap = new HashMap<Integer, String>();

                sendFlagMap.put(1, "审批后发送");
                sendFlagMap.put(2, "定时发送");
            map.put("sendFlagMap", sendFlagMap);
               Map<Integer, String> checkStateMap = new HashMap<Integer, String>();

                checkStateMap.put(1, "通过");
                checkStateMap.put(2, "未通过");
            map.put("checkStateMap", checkStateMap);
               Map<Integer, String> sendStateMap = new HashMap<Integer, String>();

                sendStateMap.put(0, "草稿");
                sendStateMap.put(2, "提交审批");
                sendStateMap.put(3, "已审批待发送");
                sendStateMap.put(4, "已发送");
            map.put("sendStateMap", sendStateMap);

			List<Column> clist = new ArrayList();
			Column cloumn = null;

            cloumn = new Column("发送ID", "sendId", 1);
			clist.add(cloumn);
            cloumn = new Column("备注", "remark", 1);
			clist.add(cloumn);
            cloumn = new Column("模板ID", "templateId", 1);
			clist.add(cloumn);
            cloumn = new Column("源号码扩展号", "sourceNum", 1);
			clist.add(cloumn);
            cloumn = new Column("发送标识", "sendFlag", 2);
			clist.add(cloumn);
            cloumn = new Column("计划发送时间", "planSendTime", 1);
			clist.add(cloumn);
            cloumn = new Column("发送电话本", "addressMobile", 1);
			clist.add(cloumn);
            cloumn = new Column("电话号码数", "mobileNum", 1);
			clist.add(cloumn);
            cloumn = new Column("spId", "spId", 1);
			clist.add(cloumn);
            cloumn = new Column("sp名称", "spName", 1);
			clist.add(cloumn);
            cloumn = new Column("发送时间", "sendTime", 1);
			clist.add(cloumn);
            cloumn = new Column("结束时间", "endTime", 1);
			clist.add(cloumn);
            cloumn = new Column("审批时间", "checkTime", 1);
			clist.add(cloumn);
            cloumn = new Column("审批状态", "checkState", 2);
			clist.add(cloumn);
            cloumn = new Column("审批意见", "checkMsg", 1);
			clist.add(cloumn);
            cloumn = new Column("审批人ID", "checkUser", 1);
			clist.add(cloumn);
            cloumn = new Column("发送状态", "sendState", 2);
			clist.add(cloumn);
            cloumn = new Column("创建用户", "createUserId", 1);
			clist.add(cloumn);
            cloumn = new Column("创建时间", "createTime", 1);
			clist.add(cloumn);
			try {
				ExcelExport export = exportList(list, clist, map);
				if (export != null) {
					this.downExcel(export, response);
					//this.downzip(export, response);
				}

			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}
